package com.itheima.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private DeptService deptService;

    @Autowired
    private EmpExprService empExprService;

    /**
     * 条件分页查询
     *
     * @param param
     * @return
     */
    @Override
    public PageResult getPageResult(EmpQueryParam param) {
        //1.设置分页、排序参数
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("update_time"));
//        //2.构造查询条件
//        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.like(StrUtil.isNotBlank(param.getName()), Emp::getName, param.getName())
//                .eq(ObjectUtil.isNotNull(param.getGender()), Emp::getGender, param.getGender())
//                .between(ObjectUtil.isNotNull(param.getBegin()) && ObjectUtil.isNotNull(param.getEnd()), Emp::getEntryDate, param.getBegin(), param.getEnd());
//        //3.发起分页查询
//        Page<Emp> pageResult = page(page, queryWrapper);

        //2+3(主流)
        Page<Emp> pageResult = this.lambdaQuery().like(StrUtil.isNotBlank(param.getName()), Emp::getName, param.getName())
                .eq(ObjectUtil.isNotNull(param.getGender()), Emp::getGender, param.getGender())
                .between(ObjectUtil.isNotNull(param.getBegin()) && ObjectUtil.isNotNull(param.getEnd()), Emp::getEntryDate, param.getBegin(), param.getEnd())
                .page(page);
        //4.对结果集进行处理
        List<Emp> records = pageResult.getRecords();
        records.forEach(emp -> {
            Dept dept = deptService.getById(emp.getDeptId());
            if (ObjectUtil.isNotNull(dept)) {
                emp.setDeptName(dept.getName());
            }
        });
        //5.返回分页结果集
        return new PageResult<>(pageResult.getTotal(), records);
    }

    /**
     * 新增员工
     *
     * @param emp
     */

    @Override
    @Transactional
    public void insertEmp(Emp emp) {
        //1.保存员工的基本信息
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        this.save(emp);
        //2.保存员工的工作经历信息
        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(expr -> expr.setEmpId(emp.getId()));
        this.empExprService.saveBatch(exprList);
    }

    /**
     * 批量删除员工（员工基本信息和员工工作经历）
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleteEmp(List<Integer> ids) {
        //1.删除员工基本信息
        this.removeBatchByIds(ids);
        //2.根据员工集合的id删除员工工作经历信息
        LambdaQueryWrapper<EmpExpr> queryWrapper = new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId, ids);
        this.empExprService.remove(queryWrapper);
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Emp queryById(Integer id) {
        //1.查询员工基本信息
        Emp emp = this.getById(id);
        //2.查询员工工作经历信息
        List<EmpExpr> empExprs = this.empExprService.lambdaQuery().eq(EmpExpr::getEmpId, id).list();
        //3.将员工工作经历返回到实体中
        emp.setExprList(empExprs);
        //4.返回员工信息实体
        return emp;
    }

    /**
     * 修改员工的基本信息（改=先删后增）
     *
     * @param emp
     */
    @Override
    @Transactional
    public void updateEmp(Emp emp) {
        //1.修改员工信息
        emp.setUpdateTime(LocalDateTime.now());
        this.updateById(emp);
        //2.删除员工工作经历信息
        this.empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));
        //3.新增员工工作经历信息
        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(expr -> expr.setEmpId(emp.getId()));
        this.empExprService.saveBatch(exprList);
    }
}
